package com.otitan.la.forest.industry.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.auth.framework.basepro.common.AuthCommon;
import com.otitan.la.forest.industry.client.http.HttpPostJSON;
import com.otitan.la.forest.industry.constant.DicEnum;
import com.otitan.la.forest.industry.constant.FilePathConstant;
import com.otitan.la.forest.industry.constant.StaticConstant;
import com.otitan.la.forest.industry.dto.EnterpriseDTO;
import com.otitan.la.forest.industry.dto.EnterpriseEntityDTO;
import com.otitan.la.forest.industry.dto.EnterpriseStatisticalDTO;
import com.otitan.la.forest.industry.dto.FileInfoDTO;
import com.otitan.la.forest.industry.entity.AssetInfoEntity;
import com.otitan.la.forest.industry.entity.EnterpriseEntity;
import com.otitan.la.forest.industry.entity.EnterpriseInputEntity;
import com.otitan.la.forest.industry.exception.CommonException;
import com.otitan.la.forest.industry.exception.FileException;
import com.otitan.la.forest.industry.handler.EnterpriseVerifyHandler;
import com.otitan.la.forest.industry.mapper.EnterpriseMapper;
import com.otitan.la.forest.industry.service.AssetInfoService;
import com.otitan.la.forest.industry.service.EnterpriseService;
import com.otitan.la.forest.industry.utils.CommonUtils;
import com.otitan.la.forest.industry.utils.*;
import com.otitan.la.forest.industry.vo.EnterpriseEntityVO;
import com.otitan.la.forest.industry.vo.EnterpriseVO;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Slf4j
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, EnterpriseEntity> implements EnterpriseService {

    @Autowired
    private EnterpriseService enterpriseService;

    @Value("${redis.key-prefix}")
    private String redisKeyPrefix;

    @Value("${sysServer.path}")
    String sysServerPath;

    @Value("${la-forest-industry.file.excel-folder-upload}")
    private String excelFolder;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private AuthCommon authCommon;
    @Autowired
    private AssetInfoService assetInfoService;

    @Transactional
    @Override
    public DataResult add(EnterpriseEntityDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EnterpriseEntity::getCode, dto.getCode());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.success("统一社会信用代码重复");
        }
        //dto转成entity后保存
        EnterpriseEntity enter = new EnterpriseEntity();
        BeanUtils.copyProperties(dto, enter);
        enter.setId(CommonUtils.getUUID());
        enter.setLicenseCode(CommonUtils.getUUID());
        enter.setCertificateCode(CommonUtils.getUUID());
        enter.setHighTechCode(CommonUtils.getUUID());
        enter.setOtherCode(CommonUtils.getUUID());
        enter.setPatentCode(CommonUtils.getUUID());
        enter.setTitleCode(CommonUtils.getUUID());
        List<FileInfoDTO> dtoList = new ArrayList<>();
        //对每个文件集合做非空判断、
        isNotEmpty(dto, dtoList, enter);
        //将文件集合save至远程系统
        String path = sysServerPath + FilePathConstant.FILE_ADD;
        HttpPostJSON postJSON = new HttpPostJSON(path, authCommon.getTokenId(), dtoList);
        postJSON.execute();
        boolean result = HttpResultUtil.getObjCode(postJSON.readStr());
        if (!result) {
            return DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        postJSON.releaseConnection();
        //添加资产信息
        editorAssetsInfo(dto, enter);
        boolean isSuccess = this.save(enter);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
    }

    private void editorAssetsInfo(EnterpriseEntityDTO dto, EnterpriseEntity enter) {
        List<AssetInfoEntity> assets = dto.getAssetsList();
        if (CollUtil.isNotEmpty(assets)) {
            assets.forEach(asset -> {
                asset.setEnterpriseId(enter.getId());
                throw new CommonException("年份不能为空");
            });
            assetInfoService.saveBatch(assets);
        }
    }

    private void isNotEmpty(EnterpriseEntityDTO dto, List<FileInfoDTO> dtoList, EnterpriseEntity enter) {
        addFileInfoList(dtoList, dto.getCertificateFile(), enter.getId(), enter.getCertificateCode());
        addFileInfoList(dtoList, dto.getLicenseFile(), enter.getId(), enter.getLicenseCode());
        addFileInfoList(dtoList, dto.getPatentFile(), enter.getId(), enter.getPatentCode());
        addFileInfoList(dtoList, dto.getTitleFile(), enter.getId(), enter.getTitleCode());
        addFileInfoList(dtoList, dto.getHighTechFile(), enter.getId(), enter.getHighTechCode());
        addFileInfoList(dtoList, dto.getOtherFile(), enter.getId(), enter.getOtherCode());
    }


    private void addFileInfoList(List<FileInfoDTO> dtoList, List<FileInfoDTO> files, String businessId, String typeCode) {
        if (CollUtil.isNotEmpty(files)) {
            files.forEach(file -> {
                if (StringUtils.isEmpty(file.getFilePath())) {
                    throw new FileException("文件路径不能为空");
                }
                file.setBusinessId(businessId);
                file.setFileTypeCode(typeCode);
                file.setIsFile(StaticConstant.IS_FILE);
            });
            dtoList.addAll(files);
        }
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        String path = sysServerPath + FilePathConstant.FILE_BUSSID_DELETE;
        HttpPostJSON postJSON = new HttpPostJSON(path, authCommon.getTokenId(), ids);
        postJSON.execute();
        boolean result = HttpResultUtil.getObjCode(postJSON.readStr());
        if (!result) {
            return DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        postJSON.releaseConnection();
        //删除资产信息
        assetInfoService.batchDelete(ids);
        this.removeByIds(ids);
        return DataResult.success();
    }

    @Override
    public DataResult editor(EnterpriseEntityDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EnterpriseEntity::getCode, dto.getCode());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("统一社会信用代码重复");
        }
        List<String> ids = new ArrayList<>();
        ids.add(dto.getId());
        String pathDelete = sysServerPath + FilePathConstant.FILE_BUSSID_DELETE;
        HttpPostJSON postJSON = new HttpPostJSON(pathDelete, authCommon.getTokenId(), ids);
        postJSON.execute();
        boolean resultDelete = HttpResultUtil.getObjCode(postJSON.readStr());
        if (!resultDelete) {
            return DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        postJSON.releaseConnection();
        //dto转成entity后保存
        EnterpriseEntity enter = new EnterpriseEntity();
        BeanUtils.copyProperties(dto, enter);
        List<FileInfoDTO> dtoList = new ArrayList<>();
        //对每个文件集合做非空判断、
        isNotEmpty(dto, dtoList, enter);
        //将文件集合save至远程系统
        String path = sysServerPath + FilePathConstant.FILE_ADD;
        HttpPostJSON post = new HttpPostJSON(path, authCommon.getTokenId(), dtoList);
        post.execute();
        HttpResultUtil.getObjCode(postJSON.readStr());
        post.releaseConnection();
        //删除资产信息
        assetInfoService.batchDelete(ids);
        //修改资产信息
        editorAssetsInfo(dto, enter);
        boolean isSuccess = this.updateById(enter);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
    }


    @Override
    public DataResult findPageData(long page, long size, EnterpriseDTO enterprise) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotEmpty(enterprise.getName())) {
            queryWrapper.like(EnterpriseEntity::getName, enterprise.getName());
        }
        if (StrUtil.isNotEmpty(enterprise.getEnterType())) {
            queryWrapper.eq(EnterpriseEntity::getEnterType, enterprise.getEnterType());
        }
        if (StrUtil.isNotEmpty(enterprise.getBatchId())) {
            queryWrapper.eq(EnterpriseEntity::getBatchId, enterprise.getBatchId());
        }
        if (StrUtil.isNotEmpty(enterprise.getAreaCode())) {
            queryWrapper.eq(EnterpriseEntity::getAreaCode, enterprise.getAreaCode());
        }
        if (StrUtil.isNotEmpty(enterprise.getManagementType())) {
            queryWrapper.eq(EnterpriseEntity::getScopeBusiness, enterprise.getManagementType());
        }
        queryWrapper.orderByDesc(EnterpriseEntity::getCreateDate);
        IPage<EnterpriseEntity> iPage = this.page(pagePlug, queryWrapper);
        IPage<EnterpriseEntityVO> iPageVO = new Page<>();
        BeanUtils.copyProperties(iPage, iPageVO);
        List<EnterpriseEntityVO> listVO = new ArrayList<>();
        // 转换使用字典的属性
        if (CollUtil.isNotEmpty(iPage.getRecords())) {
            iPage.getRecords().forEach(item -> {
                EnterpriseEntityVO vo = new EnterpriseEntityVO();
                BeanUtils.copyProperties(item, vo);
                String enterTypeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix, DicEnum.ENTERPRISETYPE.getValue(), vo.getEnterType());
                String areaCodeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix, DicEnum.AREA.getValue(), vo.getAreaCode());
                vo.setEnterTypeName(enterTypeName);
                vo.setAreaName(areaCodeName);
                listVO.add(vo);
            });
        }
        iPageVO.setRecords(listVO);
        return DataResult.success(iPageVO);
    }

    @Override
    public DataResult findPageByCodes(long page, long size, EnterpriseDTO enterprise) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotEmpty(enterprise.getName())) {
            queryWrapper.like(EnterpriseEntity::getName, enterprise.getName());
        }
        if (!CommonUtils.isEmpty(enterprise.getAreaCodes())) {
            List<String> areaCodes=getAreaCodes(enterprise.getAreaCodes(),enterprise.getAreaCodes());
            //queryWrapper.eq(EnterpriseEntity::getAreaCode, enterprise.getAreaCode());
            queryWrapper.in(EnterpriseEntity::getAreaCode,areaCodes);
        }
        if (StrUtil.isNotEmpty(enterprise.getBatchId())) {
            queryWrapper.eq(EnterpriseEntity::getBatchId, enterprise.getBatchId());
        }

        if (StrUtil.isNotEmpty(enterprise.getScopeBusiness())) {
            queryWrapper.eq(EnterpriseEntity::getScopeBusiness, enterprise.getScopeBusiness());
        }
        queryWrapper.orderByDesc(EnterpriseEntity::getCreateDate);
        IPage<EnterpriseEntity> iPage = this.page(pagePlug, queryWrapper);
        IPage<EnterpriseEntityVO> iPageVO = new Page<>();
        BeanUtils.copyProperties(iPage, iPageVO);
        List<EnterpriseEntityVO> listVO = new ArrayList<>();
        // 转换使用字典的属性
        if (CollUtil.isNotEmpty(iPage.getRecords())) {
            iPage.getRecords().forEach(item -> {
                EnterpriseEntityVO vo = new EnterpriseEntityVO();
                BeanUtils.copyProperties(item, vo);
                String enterTypeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix, DicEnum.ENTERPRISETYPE.getValue(), vo.getEnterType());
                String areaCodeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix, DicEnum.AREA.getValue(), vo.getAreaCode());
                vo.setEnterTypeName(enterTypeName);
                vo.setEnterTypeName(areaCodeName);
                listVO.add(vo);
            });
        }
        iPageVO.setRecords(listVO);
        return DataResult.success(iPageVO);
    }

    @Override
    public DataResult findOne(String id) {
        String path = sysServerPath + FilePathConstant.FILE_FIND;
        HttpPostJSON postJSON = new HttpPostJSON(path, authCommon.getTokenId(), id);
        postJSON.execute();
        List<FileInfoDTO> arrData = HttpResultUtil.getArrData(postJSON.readStr(), FileInfoDTO.class);
        if (CollUtil.isEmpty(arrData)) {
            return DataResult.fail("操作失败");
        }
        postJSON.releaseConnection();
        EnterpriseEntity entity = this.getById(id);
        EnterpriseEntityVO vo = new EnterpriseEntityVO();
        BeanUtils.copyProperties(entity, vo);
        List<FileInfoDTO> cer = new ArrayList<>();
        List<FileInfoDTO> license = new ArrayList<>();
        List<FileInfoDTO> high = new ArrayList<>();
        List<FileInfoDTO> par = new ArrayList<>();
        List<FileInfoDTO> title = new ArrayList<>();
        List<FileInfoDTO> other = new ArrayList<>();
        arrData.forEach(file -> {
            if (vo.getCertificateCode() != null && file.getFileTypeCode() != null) {
                if (file.getFileTypeCode().equals(vo.getCertificateCode())) {
                    cer.add(file);
                }
            }
            if (vo.getLicenseCode() != null && file.getFileTypeCode() != null) {
                if (file.getFileTypeCode().equals(vo.getLicenseCode())) {
                    license.add(file);
                }
            }
            if (vo.getHighTechCode() != null && file.getFileTypeCode() != null) {
                if (file.getFileTypeCode().equals(vo.getHighTechCode())) {
                    high.add(file);
                }
            }
            if (vo.getPatentCode() != null && file.getFileTypeCode() != null) {
                if (file.getFileTypeCode().equals(vo.getPatentCode())) {
                    par.add(file);
                }
            }
            if (vo.getTitleCode() != null && file.getFileTypeCode() != null) {
                if (file.getFileTypeCode().equals(vo.getTitleCode())) {
                    title.add(file);
                }
            }
            if (vo.getOtherCode() != null && file.getFileTypeCode() != null) {
                if (file.getFileTypeCode().equals(vo.getOtherCode())) {
                    other.add(file);
                }
            }
        });
        vo.setCertificateFile(cer);
        vo.setLicenseFile(license);
        vo.setHighTechFile(high);
        vo.setPatentFile(par);
        vo.setTitleFile(title);
        vo.setOtherFile(other);
        // 需要转换的具体字典属性
        String enterTypeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix, DicEnum.ENTERPRISETYPE.getValue(), vo.getEnterType());
        String areaCodeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix, DicEnum.AREA.getValue(), vo.getAreaCode());
        vo.setEnterTypeName(enterTypeName);
        vo.setAreaName(areaCodeName);
        //查询资产信息
        List<AssetInfoEntity> assets=assetInfoService.findAssets(id);
        vo.setAssetsList(assets);
        return DataResult.success(vo);
    }


    @Override
    public DataResult<Map<String, Object>> statistical(EnterpriseStatisticalDTO enterpriseStatisticalDTO) {
        Map<String, Object> objectMap = new HashMap<>();
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        queryWrapper.eq(EnterpriseEntity::getIsLeadingEnterprises, 1);
        //获取龙头企业
        List<EnterpriseEntity> enterpriseEntities = this.list(queryWrapper);
        List<EnterpriseVO> enterpriseVOS = new ArrayList<>();
        if (!CommonUtils.isEmpty(enterpriseEntities)) {
            enterpriseVOS = CommonUtils.copy(enterpriseEntities, EnterpriseVO.class);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (StringUtils.isEmpty(enterpriseStatisticalDTO.getBatchId())) {
            mapList = enterpriseMapper.findSizeByType(enterpriseStatisticalDTO);
        } else {
            mapList = enterpriseMapper.findSizeByEnterType(enterpriseStatisticalDTO);
        }
        objectMap.put("enterprises", enterpriseVOS);
        objectMap.put("enterpriseSize", mapList);
        return DataResult.success(objectMap);
    }


    @Override
    public void download(EnterpriseDTO entity, HttpServletResponse httpServletResponse) {
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();

        if (entity.getIds() != null && entity.getIds().size() > 0) {
            queryWrapper.in(EnterpriseEntity::getId, entity.getIds());
        } else {
            // 企业名称
            if (StringUtils.isNotBlank(entity.getName())) {
                queryWrapper.like(EnterpriseEntity::getName, entity.getName());
            }
            // 所在行政区编码
            if (StringUtils.isNotBlank(entity.getAreaCode())) {
                queryWrapper.eq(EnterpriseEntity::getAreaCode, entity.getAreaCode());
            }
            // 龙头企业批次
            if (StringUtils.isNotBlank(entity.getBatchId())) {
                queryWrapper.eq(EnterpriseEntity::getBatchId, entity.getBatchId());
            }
            // 企业类型
            if (StringUtils.isNotBlank(entity.getEnterType())) {
                queryWrapper.eq(EnterpriseEntity::getEnterType, entity.getEnterType());
            }
            // 经营类型
            if (StringUtils.isNotBlank(entity.getManagementType())) {
                queryWrapper.eq(EnterpriseEntity::getManagementType, entity.getManagementType());
            }
        }


        List<EnterpriseEntity> list = this.list(queryWrapper);

        List<Map<String, Object>> mapList = new ArrayList<>();
        for (EnterpriseEntity enterpriseEntity : list) {
            Map<String, Object> map = FileUtil.beanToMap(enterpriseEntity);
            mapList.add(map);
        }

        List<ExcelExportEntity> keyList = ImOrExportUtil.enterpriseExport(redisTemplate, redisKeyPrefix);

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("企业名录", "企业信息表"),
                keyList, mapList);

        String fileName = "企业信息表-" + DateUtil.getNowDateStr() + ".xls";

        FileUtil.exportExcelByDownload(workbook, httpServletResponse, fileName);

    }

    @Transactional
    @Override
    public DataResult upload(MultipartFile file) {
        String fileOriginalFilename = file.getOriginalFilename();
        String suffix = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf(".") + 1);
        if (StaticConstant.FILE_EXTENSION_XLS.equalsIgnoreCase(suffix)) {
            // 保存文件
            String path = FileUtil.uploadFile(excelFolder, file);
            ExcelImportResult<EnterpriseInputEntity> result = null;
            EnterpriseVerifyHandler verifyHandler = new EnterpriseVerifyHandler();
            verifyHandler.setEnterpriseService(enterpriseService);
            verifyHandler.setRedisKeyPrefix(redisKeyPrefix);
            verifyHandler.setRedisTemplate(redisTemplate);
            InputStream inputStream = null;
            List<EnterpriseInputEntity> enterInputs = null;
            try {
                inputStream = new FileInputStream(path);
                ImportParams params = new ImportParams();
                // 表头设置为2行
                params.setHeadRows(1);
                // 标题行设置为0行，默认是0，可以不设置
                params.setTitleRows(1);
                // 开启Excel校验
                params.setNeedVerfiy(true);
                params.setVerifyHandler(verifyHandler);
                result = ExcelImportUtil.importExcelMore(inputStream,
                        EnterpriseInputEntity.class, params);
                enterInputs = result.getList();
                List<EnterpriseEntity> enterEntities = new ArrayList<>();
                enterInputs.forEach(enterInput -> {
                    EnterpriseEntity entity = new EnterpriseEntity();
                    BeanUtils.copyProperties(enterInput, entity);
                    Map mapArea = ImOrExportUtil.getDicName(DicEnum.AREA.getValue(), redisTemplate, redisKeyPrefix);
                    String areaCode = ImOrExportUtil.mapToString(mapArea, entity.getAreaCode());
                    Map mapEnter = ImOrExportUtil.getDicName(DicEnum.ENTERPRISETYPE.getValue(), redisTemplate, redisKeyPrefix);
                    String enterCode = ImOrExportUtil.mapToString(mapEnter, entity.getEnterType());
                    entity.setAreaCode(areaCode);
                    entity.setEnterType(enterCode);
                    entity.setIsLeadingEnterprises(Integer.valueOf(enterInput.getIsLeadingEnterprises()));
                    enterEntities.add(entity);
                });
                this.saveBatch(enterEntities);
            } catch (Exception e) {
                log.error(e.getMessage());
            } finally {
                // 清除threadLocal 防止内存泄漏
                ThreadLocal<List<EnterpriseInputEntity>> threadLocal = verifyHandler.getThreadLocal();
                if (threadLocal != null) {
                    threadLocal.remove();
                }
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }

            List<EnterpriseInputEntity> failResultList = result.getFailList();
            List<String> errors = new ArrayList<>();
            if (CollUtil.isNotEmpty(failResultList)) {
                for (EnterpriseInputEntity inputEntity : failResultList) {
                    StringJoiner joiner = new StringJoiner(",");
                    joiner.add(inputEntity.getErrorMsg());
                    inputEntity.setErrorMsg(joiner.toString());
                }
                for (EnterpriseInputEntity entity : result.getFailList()) {
                    int line = entity.getRowNum() + 1;
                    String msg = "第" + line + "行的错误是：" + entity.getErrorMsg();
                    errors.add(msg);
                }
            }
            if (CollUtil.isNotEmpty(enterInputs) && CollUtil.isEmpty(failResultList)) {
                return DataResult.success("数据导入成功!");
            } else if (CollUtil.isNotEmpty(enterInputs) && CollUtil.isNotEmpty(failResultList)) {
                errors.add(0, "部分数据导入成功!");
                return DataResult.success(errors);
            } else if (CollUtil.isEmpty(enterInputs) && CollUtil.isNotEmpty(failResultList)) {
                errors.add(0, "所有数据导入失败!");
                return DataResult.success(errors);
            }
        }
        return DataResult.fail("文件格式错误");
    }

    @Override
    public boolean checkForDuplicates(String name, String code) {
        LambdaQueryWrapper<EnterpriseEntity> queryWrapper = Wrappers.lambdaQuery();
        // 企业名称
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq(EnterpriseEntity::getName, name);
        }
        int count = this.count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }


   List<String> getAreaCodes(List<String> areaList,List<String> list){
       if (areaList.size() == 0) {
           return list;
       }
       List<String> AreaCodes=enterpriseMapper.getAreaCodesByParentId(list);
       if (AreaCodes != null && AreaCodes.size() > 0) {
           list.addAll(AreaCodes);
       }
        return getAreaCodes(AreaCodes,list);
   }



}